package kr.couponplay.android.activity.search;

import kr.couponplay.android.AppContext;
import kr.couponplay.android.adapter.QueryListAdapter;
import kr.couponplay.android.domain.DealDao;
import kr.couponplay.android.domain.RecentQuery;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class DeleteOnClickListener implements OnClickListener {
	private Context context;
	private DealDao dao;
	private QueryListAdapter queryListAdapter;
	private int position;
	
	public DeleteOnClickListener(Context context, QueryListAdapter queryListAdapter, int position, DealDao dao) {
		this.context = context;
		this.dao = dao;
		this.position = position;
		this.queryListAdapter = queryListAdapter;
	}

	@Override
	public void onClick(View v) {
        DialogInterface.OnClickListener deleteListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
            	RecentQuery recentQuery = queryListAdapter.getItem(position);
            	queryListAdapter.remove(recentQuery);
            	queryListAdapter.notifyDataSetChanged();
            	deleteQuery(recentQuery);
            }
        };
         
        String message = "[" + queryListAdapter.getItem(position).getQuery() + "]를 삭제하시겠습니까?<br/>";
        new AlertDialog.Builder(context)
            .setMessage(Html.fromHtml(message))
            .setPositiveButton("삭제", deleteListener)
            .setNegativeButton("취소", null)
            .show();
	}
	
	private void deleteQuery(final RecentQuery recentQuery) {
		Thread thread = new Thread(new Runnable() {
            public void run() {
            	try {
            		dao.deleteMyRecentQuery(recentQuery.getSid(), recentQuery.getQuery());
            	} catch (Exception e) {
            		Log.e(AppContext.TAG, e.getMessage(), e);
            	}
            }
        });
        thread.start();
	}
}
